package com.lifl.b328.garden.model;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class LoginActivity extends Activity {
	
	protected static final int ADD_ACCOUNT  = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listecompte);
		final AccountManager am = AccountManager.get(this);
		Account[] list = am.getAccountsByType("com.google");
		MonLog.print("onCreate", getClass());
		if(list.length == 0)
			startActivityForResult(new Intent(Settings.ACTION_ADD_ACCOUNT), ADD_ACCOUNT);
		else
			afficheListe(list);
	}
	
	private void afficheListe(final Account[] list){
		ListView lv = (ListView) findViewById(R.id.listviewcompte);
		String [] compte = new String[list.length];
		for(int i = 0; i < list.length;i++)
			compte[i] = list[i].name;
		ArrayAdapter<String> ada = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,compte);
		lv.setAdapter(ada);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Account account = list[arg2];
				Intent intent = new Intent();
				intent.putExtra("account",account);
				setResult(RESULT_OK,intent);
				finish();
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		setResult(RESULT_CANCELED,new Intent());
		
	}
}
